package com.example.demo.service;


import com.example.demo.bean.RegionStates;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class DataProvider{

    private static Logger logger = LoggerFactory.getLogger(DataProvider.class);
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(cron = "${lsf.Schedules.updateVirusDataCron}")
    public CSVParser getCSV() throws IOException {
        String url = "https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";
        RequestEntity<Void> requestEntity = RequestEntity
                .get(URI.create(url))
                .headers(httpsHeaders -> httpsHeaders.add("User-Agent", "Mozilla/5.0"))
                .build();
        ResponseEntity<Resource> exchange = new RestTemplate().exchange(requestEntity, Resource.class);
        Resource body = exchange.getBody();
        logger.info("数据长度：{}", body.contentLength());
        logger.info("The time is now {}", dateFormat.format(new Date()));
        Reader reader = new InputStreamReader(body.getInputStream(), "UTF-8");
        CSVParser parser = new CSVParser(reader, CSVFormat.EXCEL.withHeader());
        return parser;
    }

    public List<RegionStates> getRegionStates(String str) throws IOException {
        CSVParser records = getCSV();
        List<RegionStates> res = new LinkedList<>();
        for (CSVRecord record: records) {
            String state = record.get("Province/State");
            String country = record.get("Country/Region");
            String longitude=record.get(2);
            String dimension=record.get(3);
            int num1 = Integer.parseInt(record.get(record.size()-1));
            int num2 = num1 - Integer.parseInt(record.get(record.size()-2));
            if(country.equals(str))
                res.add(new RegionStates(state, country, num1, num2,longitude,dimension));
        }
        return res;
    }

    public List<RegionStates> getAllRegionStates() throws IOException {
        CSVParser records = getCSV();
        List<RegionStates> res = new LinkedList<>();
        for (CSVRecord record: records) {
            String state = record.get("Province/State");
            String country = record.get("Country/Region");
            String longitude=record.get(2);
            String dimension=record.get(3);
            int num1 = Integer.parseInt(record.get(record.size()-1));
            int num2 = num1 - Integer.parseInt(record.get(record.size()-2));
            res.add(new RegionStates(state, country, num1, num2,longitude,dimension));
        }
        return res;
    }

    public Map<String, List<RegionStates>> addAllRegion() throws IOException {
        CSVParser records = getCSV();
        Map<String, List<RegionStates>> map = new HashMap<>();
        for(CSVRecord record : records) {
            String state = record.get("Province/State");
            String country = record.get("Country/Region");
            String longitude=record.get(2);
            String dimension=record.get(3);
            int num1 = Integer.parseInt(record.get(record.size()-1));
            int num2 = num1 - Integer.parseInt(record.get(record.size()-2));
            if(map.containsKey(country))
            {
                List<RegionStates> regionStates = map.get(country);
                regionStates.add(new RegionStates(state, country, num1, num2,longitude,dimension));
            }else
            {
                List<RegionStates> list = new LinkedList<>();
                list.add(new RegionStates(state, country, num1, num2,longitude,dimension));
                map.put(country, list);
            }
        }
        return map;
    }

    public List<RegionStates> getNum() throws IOException {
        Map<String, List<RegionStates>> listMap = addAllRegion();
        List<RegionStates> list = new LinkedList<>();
        Iterator<String> iterator = listMap.keySet().iterator();
        while(iterator.hasNext())
        {
            String country = iterator.next();
            List<RegionStates> list1 = listMap.get(country);
            int num1 = 0;
            int num2 = 0;
            for(RegionStates state : list1)
            {
                num1 += state.getLatestTotalCases();
                num2 += state.getDiffFromPrevDay();
            }
            list.add(new RegionStates(null, country, num1, num2,null,null));
        }
        return list;
    }

}
